<?php

	namespace Phptricks\app\models\groups;

/*
	 * To change this license header, choose License Headers in Project Properties.
	 * To change this template file, choose Tools | Templates
	 * and open the template in the editor.
	 * Description of groups
	 *
	 */
	use Phptricks\system\library\models\models as models;
	use Phptricks\system\library\PhptricksExceptions\PhptricksExceptions as Exc;
	use Phptricks\system\core\library\library;

	class groups extends models implements library{

		private static $_instance = null;
		private $table_name = 'groups';

		public static function &getinstance(){
			if (self::$_instance === null) {
				self::$_instance = new \Phptricks\app\models\groups\groups();
			}
			return self::$_instance;
		}

		/**
		 * 
		 * @param type $array_data
		 * @return type
		 */
		public function addgroup($array_data = array()){
			return $this->insert($this->table_name, $array_data);
		}

		/**
		 * 
		 * @param array $array_data
		 * @param array|string $where
		 */
		public function updatedata($array_data = array(), $where = ''){
			$this->update($this->table_name, $array_data, $where);
		}

		/**
		 * 
		 * @param array $array_data
		 */
		public function deletegroups($array_data){
			$this->delete($this->table_name, $array_data);
		}

		/**
		 * 
		 * @param array|string $array_where
		 * @param string $order_by order by field name
		 * @return array data of groups
		 * @throws Exc 
		 */
		public function get_groups($array_where = array(), $order_by = 'group_id', $getcount = false){
			$fields = '';
			if ($getcount == true) {
				$fields = 'groups.*, (SELECT COUNT(users.user_id) as count_users FROM users WHERE users.user_group_id = groups.group_id) as count_users ';
			}
			try {
				$this->select($fields, $this->table_name);
				$this->where($array_where);
				$data = $this->execute('', $order_by);
				return $data;
			} catch (\Exception $exc) {
				throw new Exc($exc->getMessage());
			}
		}

		/**
		 * 
		 * @param array|string $id 
		 * @param string $order_by
		 * @return array data of groups
		 * @throws Exc
		 */
		public function get_groups_by_id($id, $order_by = 'group_id'){
			try {
				if (!isset($id) || empty($id)) {
					throw new Exc('this prama $id is not set');
				}
				$array_where = array(
					'group_id' => \intval($id),
				);
				if (\is_array($id)) {
					$array_where = array(
						'group_id' => \array_filter($id, function(&$k) {
									return $k = \intval($k);
								}),
					);
				}
				$data = $this->get_groups($array_where, $order_by);
				return $data;
			} catch (\Exception $exc) {
				throw new Exc($exc->getMessage());
			}
		}

		public function move_users($array_where){
			
		}

	}
	